package com.wzdigit.wms.raw.service.backtosap;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wzdigit.framework.Shift;
import com.wzdigit.mes.basic.api.BasicVendorApi;
import com.wzdigit.mes.basic.dto.VendorDTO;
import com.wzdigit.wms.basic.domain.asn.AsnDtl;
import com.wzdigit.wms.basic.domain.asn.AsnDtlGoods;
import com.wzdigit.wms.basic.domain.asn.AsnHeader;
import com.wzdigit.wms.basic.domain.basic.Sku;
import com.wzdigit.wms.basic.domain.basic.Warehouse;
import com.wzdigit.wms.basic.domain.mapping.CodeMapping;
import com.wzdigit.wms.basic.domain.mid.IfPostback;
import com.wzdigit.wms.basic.domain.transfer.GdnDtl;
import com.wzdigit.wms.basic.domain.transfer.GdnHeader;
import com.wzdigit.wms.basic.enums.AsnTypeEnum;
import com.wzdigit.wms.basic.enums.GdnTypeEnum;
import com.wzdigit.wms.basic.enums.writeback.BackResultEnum;
import com.wzdigit.wms.basic.enums.writeback.OtherSystemEnum;
import com.wzdigit.wms.basic.enums.writeback.TopicEnum;
import com.wzdigit.wms.basic.mapper.core.basic.SkuMapper;
import com.wzdigit.wms.basic.mapper.core.basic.WarehouseMapper;
import com.wzdigit.wms.basic.mapper.core.mapping.CodeMappingMapper;
import com.wzdigit.wms.basic.mapper.core.order.AsnDtlGoodsMapper;
import com.wzdigit.wms.basic.service.code.CodeMappingService;
import com.wzdigit.wms.common.entity.StatusCode;
import com.wzdigit.wms.raw.client.response.gdn.delivery.DeliveryGoodsResponse;
import com.wzdigit.wms.raw.client.response.gdn.delivery.SimpleGdnDtl;
import com.wzdigit.wms.raw.service.mid.IfPostbackService;
import com.wzdigit.wms.web.service.wms2sap.getandreturnmaterial.ZDT_066_ReqRECORDS;
import com.wzdigit.wms.web.service.wms2sap.outstore.ZDT_071_ReqCDK;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/*
    生产领退料回写(含易损件)
    * @author shuaic
    * @date 2021/6/22 13:35
*/
@Service
@Slf4j
public class GetAndReturnMaterialBackService {

    @Autowired
    IfPostbackService ifPostbackService ;

    @Autowired
    private CodeMappingService codeMappingService;

    @Autowired
    SkuMapper skuMapper ;

    @Autowired
    CodeMappingMapper codeMappingMapper ;

    @Autowired
    WarehouseMapper warehouseMapper ;

    @Autowired
    AsnDtlGoodsMapper asnDtlGoodsMapper ;

    @Reference(version = "${dubbo.consumers.basic.vendor.api:1.0.0}", check = false, timeout = 300000)
    private BasicVendorApi basicVendorApi;



    /*易损件领退料回写 GDN
     * @param header 表头
     * @param dtlList 明细
     * @return void
     * @author shuaic
     * @date 2021/6/22 13:39
     */
    public void getAndReturnMaterialBack(GdnHeader header, List<GdnDtl> dtlList ){

        //生成回写数据
        List<ZDT_066_ReqRECORDS>  list = new ArrayList<>();
        for(GdnDtl dtl  : dtlList){
            ZDT_066_ReqRECORDS record = new ZDT_066_ReqRECORDS();
            record.setZPCKNO(header.getGdnNo());
            record.setGUID(dtl.getGdnLineNo()+"");
            record.setZTYPE("D"); //领退料类型？
            record.setZFLAG("3");//回写状态？
            record.setENMNG(dtl.getOrderQty()+"");//发货数量
            record.setAUDITUSER(header.getGdnApprovedUser());//审核人
            record.setAUDITTIME(DateUtil.format(header.getGdnApprovedTime(),"yyyyMMdd"));//审核时间
            list.add(record);
        }
        String jsonString = JSON.toJSONString(list);

        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_GET_AND_RETURN.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }
    }


    /*易损件领退料回写 ASN
     * @param header 表头
     * @param dtlList 明细
     * @return void
     * @author shuaic
     * @date 2021/6/22 13:39
     */
    public void getAndReturnMaterialBack(AsnHeader header, List<AsnDtl> dtlList ){
        long wmsId = new Date().getTime();
        //生成回写数据
        List<ZDT_066_ReqRECORDS>  list = new ArrayList<>();
        for(AsnDtl dtl  : dtlList){
            ZDT_066_ReqRECORDS record = new ZDT_066_ReqRECORDS();
            record.setZPCKNO(header.getAsnNo());
            if(AsnTypeEnum.R11.code.equals(header.getAsnType())){//生产退料这个行号存在自定义字段5
                record.setGUID(dtl.getAsnRef5());
            }else{
                record.setGUID(dtl.getAsnLineNo());
            }
            record.setZTYPE(header.getSourceType()); //领退料类型？
            record.setZFLAG("2");//回写状态？2正常 3 拣货中
            //统计数量
            BigDecimal totalQty = asnDtlGoodsMapper.selectSumQtyByDtlId(dtl.getAsnDtlId());
            if(totalQty.compareTo(BigDecimal.ZERO)==0){//0的不传
                continue;
            }
            record.setENMNG(totalQty.toString());//发货数量
            record.setAUDITUSER(header.getAsnCreateUser());//审核人
            record.setAUDITTIME(DateUtil.format(header.getAsnApprovedTime(),"yyyyMMdd"));//审核时间
            record.setRSV3(header.getAsnRef1());
            record.setRSV4(header.getAsnRef2());
            record.setRSV5(header.getFactory());// 领料单工厂
            record.setRSV6(header.getFactory());//实物工厂
            record.setRSV7(wmsId+"");//WMSID
            list.add(record);
        }
        String jsonString = JSON.toJSONString(list);
        log.info("调用生产领退料接口 回传的数据为==》"+jsonString);
        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setPostbackNo(header.getAsnNo());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_GET_AND_RETURN.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }
    }



    public void gdnWriteBackToSap(GdnHeader header, Map<BigDecimal, List<SimpleGdnDtl>> dtlCollectMap, Map<BigDecimal, List<DeliveryGoodsResponse>> goodsCollectMap) {

        //String wmsId = UUID.randomUUID().toString().replace("-","");传时间戳
        long wmsId = new Date().getTime();
        //生成回写数据
        List<ZDT_066_ReqRECORDS>  list = new ArrayList<>();
        for (Map.Entry<BigDecimal, List<SimpleGdnDtl>> entry : dtlCollectMap.entrySet()) {

            BigDecimal key = entry.getKey();//明细ID
            SimpleGdnDtl dtl = entry.getValue().get(0);//出库单明细
            List<DeliveryGoodsResponse> goodsList = goodsCollectMap.get(key);
            //根据组织分组
            Map<String, List<DeliveryGoodsResponse>> factoryGoodsMap = goodsList.stream().collect(Collectors.groupingBy(DeliveryGoodsResponse::getFactory));
            for (Map.Entry<String, List<DeliveryGoodsResponse>> item : factoryGoodsMap.entrySet()) {
                String facotory  = item.getKey();//组织
                List<DeliveryGoodsResponse> factoryGoodList = item.getValue();
                //对应组织对应的产品数量
                BigDecimal totalQty = factoryGoodList.stream().map(DeliveryGoodsResponse::getQty)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                if(totalQty.compareTo(BigDecimal.ZERO)==0){//0的不传
                    continue;
                }
                ZDT_066_ReqRECORDS record = new ZDT_066_ReqRECORDS();

                //获取明细交货数量34800D98A1601EDBBFC74A19627A4023
                record.setENMNG(totalQty+"");
                record.setZPCKNO(header.getGdnNo());
                //行号 生产领退料存在
                //设置行号生产领退料行号设置的在自定义字段5
                record.setGUID(dtl.getGdnRef5());
                //先分开设置 后面再撸捋一捋
                switch (header.getGdnType()){
                    case "D02" :
                        record.setGUID(dtl.getGdnRef5());
                        break;
                    case "D21" :
                        record.setGUID(dtl.getGdnRef5());
                        break;
                    case "D28" :
                        record.setGUID(dtl.getGdnRef5());
                        break;
                    default:
                        record.setGUID(dtl.getSourceShipNoticeItem());
                        break;
                }


                record.setZTYPE(header.getSourceType()); //领退料类型？
                record.setZFLAG("2");//回写状态？2正常 3 拣货中
                record.setRSV3(header.getGdnRef1());
                record.setRSV4(header.getGdnRef2());
                record.setRSV5(header.getFactory());// 领料单工厂
                record.setRSV6(facotory);//实物工厂

                record.setRSV7(wmsId+"");//WMSID
                record.setAUDITUSER(header.getGdnCreateUser());//审核人
                record.setAUDITTIME(DateUtil.format(new Date(),"yyyyMMdd"));//审核时间
                list.add(record);
            }
        }

        String jsonString = JSON.toJSONString(list);

        //插入数据到待回传数据表
        IfPostback ifPostback = new IfPostback();
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        ifPostback.setPostbackNo(header.getGdnNo());
        ifPostback.setPostbackTopic(TopicEnum.TOPIC_SAP_GET_AND_RETURN.getEnumName());
        ifPostback.setPostbackContent(jsonString);
        ifPostback.setPostbackResult(BackResultEnum.DEFAULT_STATE.getCode());
        ifPostback.setCreateTime(new Date());
        ifPostback.setDestSystem(OtherSystemEnum.SYSYTEM_SAP.getEnumName());
        try {
            ifPostbackService.addOne(ifPostback);//保存
        } catch (Exception e) {
            e.printStackTrace();
            Shift.fatal(StatusCode.SERVER_MODIFY_ERROR);
        }
    }
}
